package danran.dbapi.service;

import danran.dbapi.mapper.IPMapper;
import danran.dbapi.utils.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Classname IPService
 * @Description TODO
 * @Date 2022/1/13 17:11
 * @Created by RanCoder
 */
@Service
public class IPService {
    @Autowired
    private IPMapper ipMapper;

    @Transactional
    public void on(String mode, String ip) {
        ipMapper.turnOn(mode);
        ipMapper.saveIP(ip, mode);
        Cache.status = null;
    }

    @Transactional
    public void off() {
        ipMapper.turnoff();
        Cache.status = null;
    }

    /**
     * 返回防火墙的状态信息，白名单和黑名单
     */
    public Map<String, String> detail() {
        if (Cache.status == null) {
            List<Map<String, String>> ipRule = ipMapper.getIPRule();
            Map<String, String> status = ipMapper.getStatus();
            ipRule.forEach(i -> {
                String type = i.get("type");
                String ip = i.get("ip");
                if ("white".equals(type)) {
                    status.put("whiteIP", ip);
                } else if ("black".equals(type)) {
                    status.put("blackIP", ip);
                }
            });
            Cache.status = status;
            return status;
        } else {
            return Cache.status;
        }
    }

    public boolean check(String mode, String ipList, String originIP) {
        Set<String> ips = Arrays.stream(ipList.split("\n"))
                .map(String::trim)
                .filter(s -> !"".equals(s))
                .collect(Collectors.toSet());
        if ("black".equals(mode)) {
            return !ips.contains(originIP);
        } else if ("white".equals(mode)) {
            return ips.contains(originIP);
        }
        return false;
    }
}
